#id1 前，default=0; id2 后，default=last.id; pa, 必须有except.yml
namespace :bld do
  desc "Export to CSV"
  task :export_to_csv => :environment do
    puts time = Time.now
    pa = ENV['pa'] ? "#{BILI_PRO_PATH}#{ENV['pa']}\\" : nil
    step_index = 0
    id1 = ENV['id1'].to_i
    id2 = ENV['id2'] || Scan.last.id
    except_ids = pa ? YAML.load(open(File.join(pa + "except.yml"))) : [-1]
    except_ids << Weekly.latest.wid
    #=====================================================================
    puts "step #{step_index += 1}"
    results1 = Result.find :all, :include => :work,
                           :conditions => ["results.scan_id = ? and works.status = 1", id1]
    results2 = Result.find :all, :include => :work,
                           :conditions => ["results.scan_id = ? and works.status = 1 and works.wid not in (?) and works.ac_type_id != 18", id2, except_ids]
    puts "#{Time.now - time} seconds passed.."
    #=====================================================================
    puts "step #{step_index += 1}"
    results = {}
    results2.each{|r2| results[r2.work.id] = r2}
    unless results1.empty?
      results1.each do |r1|
        if results[r1.work.id]
          results[r1.work.id].clicks -= r1.clicks
          results[r1.work.id].comments -= r1.comments
          #results[r1.work.id].danmu -= r1.danmu.to_i
          results[r1.work.id].stows -= r1.stows.to_i
          results[r1.work.id][:old] = true
        end
      end
      #删除错误数据
      scan1 = Scan.find_by_id id1
      results.select{|i, r| r.work.cdate < scan1.created_at && !r[:old]}.each do |i, r|
        check_result = Result.find(:first, :conditions => ["work_id = ? and scan_id < ?", r.work.id, id1], :order => "id desc")
        if check_result && check_result.clicks > 100
          puts r.work.wid
          results.delete i
        end
      end
    end
    #=====================================================================
    puts "step #{step_index += 1}" #计算分数
    @@space_fix_cache ||= PStore.new("#{RAILS_ROOT}/config/space_fix_cache")
    @@space_fix_cache.transaction do
      results.values.each{|r| r[:point] = r.get_ranking_point}
      #=====================================================================
      puts "step #{step_index += 1}" #排序
      c_rank = nil
      l_id = nil
      #点击序
      results.values.sort_by{|r| r.clicks}.reverse.each_with_index do |r, i|
        c_rank = i + 1 if i == 0 || results[r.work.id].clicks != results[l_id].clicks
        l_id = r.work.id
        results[r.work.id][:click_rank] = c_rank
      end
      #评论序
      results.values.sort_by{|r| r.comments}.reverse.each_with_index do |r, i|
        c_rank = i + 1 if i == 0 || results[r.work.id].comments != results[l_id].comments
        l_id = r.work.id
        results[r.work.id][:comment_rank] = c_rank
      end
      #Part序
      results.values.sort_by{|r| r.work.part_count}.reverse.each_with_index do |r, i|
        c_rank = i + 1 if i == 0 || results[r.work.id].work.part_count != results[l_id].work.part_count
        l_id = r.work.id
        results[r.work.id][:part_rank] = c_rank
      end
      #收藏序
      results.values.sort_by{|r| r.stows.to_i}.reverse.each_with_index do |r, i|
        c_rank = i + 1 if i == 0 || results[r.work.id].stows != results[l_id].stows
        l_id = r.work.id
        results[r.work.id][:stow_rank] = c_rank
      end
      #Point序
      results.values.sort_by{|r| r[:point]}.reverse.each_with_index do |r, i|
        c_rank = i + 1 if i == 0 || results[r.work.id][:point] != results[l_id][:point]
        l_id = r.work.id
        results[r.work.id][:point_rank] = c_rank
      end
      #=====================================================================
      puts "step #{step_index + 1}" #write csv
      doc = File.new(pa ? pa + "_list.csv" : "#{RAILS_ROOT}/_list.csv", 'w')
      str = "总分排名,总分,id,标题,类别,投稿人,点击,点击排名,评论,评论排名,收藏,收藏排名,P,附加修正\n"
      results.values.sort_by{|r| r[:point_rank]}.each do |r|
          str << %(#{r['point_rank']},#{r['point']},)
          str << %(#{r.work.wid},"#{r.work.name.gsub(/"/, '""')}",#{r.work.ac_type.name},"#{r.work.author_name.gsub(/"/, '""')}",)
          str << %(#{r.clicks},#{r['click_rank']},#{r.comments},#{r['comment_rank']},)
          str << %(#{r.stows},#{r['stow_rank']},)
          str << %(#{r.work.part_count},#{r.space_fix if r.space_fix < 1})
          str << "\n"
      end 
      doc.write str
    end
    puts "#{Time.now - time} second complete"
  end
end
